<?php

namespace App\Http\Controllers\Web\Issue;

use App\Http\Responses\RespondsJson;
use App\Models\Issue\IssueOption;
use App\Models\Issue\IssueService;
use App\Models\Issue\OptionService;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class OptionController extends Controller
{
    use RespondsJson;

    protected $option;
    protected $issue;

    public function __construct(OptionService $option, IssueService $issue)
    {
        $this->option = $option;
        $this->issue = $issue;
    }

    public function many()
    {
    }

    public function bind(Request $request, $id)
    {
        if (!$this->issue->has($id)) {
            abort(404, 'Issue not found.');
        }

        $this->runValidate($request);

        $data = [
            'issue_id' => $id,
            'info' => $request->input('info'),
        ];

        if ($this->option->createAndGetId($data)) {
            return $this->respondJson('答案添加成功');
        }

        return $this->respondJson('答案添加失败', 406);
    }

    public function update(Request $request, $iid, $id)
    {
        $this->runValidate($request);

        if ($this->option->update($id, $request->all())) {
            return $this->respondJson('修改成功');
        }

        return $this->respondJson('修改失败', 406);
    }

    public function unbound($iid, $id)
    {
        if ($this->option->delete($id)) {
            return $this->respondJson('删除成功');
        }

        return $this->respondJson('删除失败', 406);
    }

    public function sort(Request $request, $iid, $id)
    {
        $this->validate($request, [
            'sort' => 'required|integer',
        ], [
            'sort.required' => '必须填写排序值',
            'sort.integer' => '排序值必须为整数',
        ]);

        if ($this->option->update($id, $request->all())) {
            return $this->respondJson('设置成功');
        }

        return $this->respondJson('设置失败', 406);
    }

    public function setCorrect($id)
    {
        $id += 0;

        if ($this->option->update($id, ['is_correct' => IssueOption::CORRECT_YES])) {
            return $this->respondJson('设置成功');
        }

        return $this->respondJson('设置失败', 406);
    }

    protected function runValidate(Request $request)
    {
        $this->validate($request, [
            'info' => 'required|max:255',
            'votes' => 'integer',
            'is_correct' => 'in:0,1',
            'sort' => 'integer',
        ], [
            'info.required' => '请填写选项',
            'info.max' => '不能超过255字',
        ]);
    }
}
